package net.wicp.tams.common.binlog.dump.listener;

import java.util.Arrays;
import java.util.Map;
import java.util.Properties;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.LoggerUtil;
import net.wicp.tams.common.apiext.jdbc.JdbcData;
import net.wicp.tams.common.apiext.jdbc.JdbcDatas;
import net.wicp.tams.common.apiext.jdbc.MySqlAssit;
import net.wicp.tams.common.apiext.jdbc.JdbcDatas.Builder;
import net.wicp.tams.common.apiext.jdbc.OptType;
import net.wicp.tams.common.binlog.dump.bean.DumpEvent;
import net.wicp.tams.common.constant.JvmStatus;
import net.wicp.tams.common.jdbc.DruidAssit;

@Slf4j
public class SenderMysql implements IBusiSender<DumpEvent> {
	
	private Properties props;

	@Override
	public void init(String dumpId) {
		this.props = Conf.getPreToProp("common.binlog.alone.dump.destination." + dumpId + ".mysql", true);
		DruidAssit.getDataSourceNoConf(dumpId, this.props);
	}

	@Override
	public void doSend(DumpEvent dumpEvent) {
		Builder newBuilder = JdbcDatas.newBuilder();
		newBuilder.addAllCols(Arrays.asList(dumpEvent.getDump().getNeedCols()));
		newBuilder.setDb(this.props.getProperty("db"));
		newBuilder.setTb(this.props.getProperty("tb"));
		newBuilder.setOptType(OptType.update);
		newBuilder.addAllKeys(Arrays.asList(dumpEvent.getDump().getPrimarys()));
		for (int i = 0; i < dumpEvent.getDump().getNeedCols().length; i++) {
			newBuilder.putType(dumpEvent.getDump().getNeedCols()[i], dumpEvent.getDump().getNeedColTypes()[i].name());
		}
		for (Map<String, String> data : dumpEvent.getDatas()) {
			net.wicp.tams.common.apiext.jdbc.JdbcData.Builder jdbcDataBuild = JdbcData.newBuilder();
			jdbcDataBuild.putAllValue(data);
			newBuilder.addDatas(jdbcDataBuild);
		}
		
		
		Result temp = MySqlAssit.dataChange(DruidAssit.getConnection(dumpEvent.getDump().getId()), newBuilder.build());
		if (!temp.isSuc()) {
			log.error("同步错误,原因：{}", temp.getMessage());
			LoggerUtil.exit(JvmStatus.s15);
		}
	}

}
